import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = 'Bearer ' + store.getters.token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    // console.log(response)
    const {
      data: { code, message: data }
    } = response
    return { code, data }
  },
  (err) => {
    console.log(err)
    // 500 、401 、403
    if (err.response && err.response.status === 403) {
      Message.error('服务禁止访问，请联系管理员')
    } else if (err.response && err.response.status === 404) {
      Message.error('资源访问有误')
    } else {
      Message.error('服务器请求有误')
    }
    return Promise.reject(err)
  }
)

export default service
